<template>
  <div>
    <el-dialog
     v-drag
    width="40%"
    :title="!dataForm.brandId ? '新增品牌' : '修改品牌'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
        label-width="80px">
        <el-form-item label="品牌名称" prop="brandName">
          <el-input size="mini" @blur="initPinYin()" v-model="dataForm.brandName" placeholder="品牌名称"></el-input>
        </el-form-item>
        <el-form-item label="品牌logo" prop="pics">
          <el-upload
            :action="uploadUrl"
            :on-preview="handleImgPreview"
            :on-remove="handleImgRemove"
            :on-success="handImgSuccess"
            :before-upload="handleBeforeUpload"
            :headers="headers"
            :file-list="dataForm.pics"
            :drag="false"
            list-type="picture"
            name="file"
            :data="uploadData">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="首字母" prop="firstLetter">
          <el-input size="mini" disabled v-model="dataForm.firstLetter" placeholder="检索首字母"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input size="mini" type="number" v-model="dataForm.sort" placeholder="排序"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="descript">
          <el-input size="mini" v-model="dataForm.descript" placeholder="介绍"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="visible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-drag title="图片预览" :visible.sync="imgDialogVisible" width="50%">
      <el-image style="width: 100%;" :src="previewPath" ></el-image>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          brandId: null,
          brandName: '',
          logo: '',
          firstLetter: '',
          sort: '',
          pics: [],
          descript: ''
        },
        previewPath: '',
        imgDialogVisible: false,
        uploadUrl: window.SITE_CONFIG.baseUrl + '/common/upload',
        headers: {
          Authorization: "Bearer " + this.$cookie.get('token'),
          token: this.$cookie.get('token')
        },
        uploadData: {
          file: ''
        },
        dataRule: {
          brandName: [
            { required: true, message: '品牌名称不能为空', trigger: 'blur' }
          ],
          // pics: [{
          //   required: true,
          //   message: '品牌logo地址不能为空',
          //   trigger: 'blur'
          // }]
        }
      }
    },
    methods: {
      init (brandId) {
        console.log("brandId==", brandId)
        this.dataForm.brandId = brandId
        this.visible = true
        this.$nextTick(async () => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.brandId) {
            const res = await this.$http({
              url: `/product/brand/info/${this.dataForm.brandId}`,
              method: 'get',
              params: this.$http.adornParams()
            })
            let data = res.data
            if (data && data.code === 0) {
                this.dataForm = data.productBrand
            }
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate(async (valid) => {
          if (valid) {
            const res = await this.$http({
              url:`/product/brand/${!this.dataForm.brandId ? 'save' : 'update'}`,
              method: 'post',
             data: this.$http.adornData( this.dataForm)
            })
            let data = res.data
            if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                }
            })
            } else {
                this.$message.error(data.msg)
            }
          }
        })
      },
      handleImgPreview(file, fileList) {
        this.previewPath = file.url
        this.imgDialogVisible = true
      },
      //图片删除
      handleImgRemove(file, fileList) {
        //找到索引
        const index = this.dataForm.pics.findIndex(item =>
          item.url === file.url
        )
        //根据索引删除
        this.dataForm.pics.splice(index, 1)
      },
      //上传之前
      handleBeforeUpload(file){
        this.curPic = {
          "name": file.name,
          "size": file.size,
          "type": file.type,
          "uid": file.uid,
          "status": 1,
        }
      },
      //上传成功
      handImgSuccess(response) {
        if (response.code === 0) {
          this.curPic.url = response.data
          this.dataForm.pics.push(this.curPic)
        }
      },
      initPinYin(){
        let name = this.dataForm.brandName
        this.$pinyin.setOptions({checkPolyphone:false,charCase:0});
        this.dataForm.firstLetter = this.$pinyin.getCamelChars(name)
        if(this.dataForm.firstLetter){
          this.dataForm.firstLetter = this.dataForm.firstLetter.substring(0,1)
        }
      }
    }
  }
</script>
